package com.kuaimacode.kframework.admin.controller.master;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.admin.services.agent.SysAgentService;
import com.kuaimacode.kframework.admin.services.category.AgentServService;
import com.kuaimacode.kframework.admin.services.master.MasterService;
import com.kuaimacode.kframework.admin.services.role.SysAdminRoleService;
import com.kuaimacode.kframework.admin.services.role.UserMapRoleService;
import com.kuaimacode.kframework.admin.services.role.UserRoleService;
import com.kuaimacode.kframework.admin.services.user.OrderService;
import com.kuaimacode.kframework.admin.services.user.UserService;
import com.kuaimacode.kframework.admin.vo.request.MasterReq;
import com.kuaimacode.kframework.admin.vo.request.OrderReq;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.mapper.user.UserRoleMapper;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessage;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessageCh;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.master.UserMasterData;
import com.kuaimacode.kframework.mybatis.models.sys.Dict;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.mybatis.models.user.UserRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @author Administrator
 * @date 2019/04/06
 */
/**
 * Controller
 */
@Controller
@RequestMapping({"/master"})
public class MasterController {
	private static String PAGE_FILE_NAME = "master/";

	@Autowired
	private MasterService masterServices;

	@Autowired
	private SysAdminRoleService adminRoleService;

	@Autowired
	private UserRoleService roleService;

	@Autowired
	private UserMapRoleService mapRoleService;

	@Autowired
	private UserService userService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private AgentServService agentServService;

	@Value("${img.upload.location.img}")
	private String imgUploadLocation;
	@Value("${project.domain}")
	private String domain;


	@RequestMapping(value = {"/index"})
	public String index(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
						@RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
						MasterReq masterReq, ModelMap model) {
		PageInfo<UserMasterData> pageInfo = masterServices.findMasterAll(masterReq,pageNum, pageSize);
		// pageInfo.list master
		model.put("pageInfo", pageInfo);
		model.put("masterReq", masterReq);
		return PAGE_FILE_NAME + "index";
	}


	@RequestMapping(value = "/agree/{id}", method = RequestMethod.POST)
	@Transactional
	@ResponseBody
	public JsonResult add(@PathVariable String id, ModelMap map) {
		try {
			UserMaster master = masterServices.getById(id);
			if (master!=null){
				master.setAuthStatus("1");
				if (masterServices.updateById(master)){
					//查找角色
					QueryWrapper<UserRole> rolw = new QueryWrapper<>();
					rolw.eq("role_name","ROLE_MASTER");
					UserRole ro= roleService.getOne(rolw);
					String[] permissionIds = {String.valueOf(ro.getId())};
					//分配角色
					mapRoleService.grantRole(String.valueOf(master.getUserId()),permissionIds);
					//更新用户表
					User user = userService.getById(master.getUserId());
					if (user !=null){
						user.setIsMaster(2);
						userService.updateById(user);
					}
				}
			}
		}catch (Exception ex){
			return JsonResult.failure(ex.getMessage());
		}
		return JsonResult.success();
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable String id, ModelMap map) {
		UserMaster master = masterServices.getById(id);
		map.put("master", master);
		map.put("isAdd", false);
		return PAGE_FILE_NAME+"form";
	}

	@RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
	@ResponseBody
	public JsonResult edit(UserMaster master, Boolean isAdd,ModelMap map) {
		try {
			if(isAdd){
				// 新建保存
				masterServices.save(master);
			}else{
				// 编辑保存
				masterServices.updateById(master);
			}
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}


	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detail(@PathVariable String id, ModelMap map) {
		MasterMessage master = new MasterMessage();
		List<MasterMessage> masters = masterServices.findAllMasterMessage(Long.parseLong(id));
		MasterMessageCh ch = new MasterMessageCh();
		if (CollectionUtils.isNotEmpty(masters)){
			master = masters.get(0);
			if (StringUtils.isNotEmpty(master.getSkillPic())){
				master.setSkillPic(domain+imgUploadLocation+master.getSkillPic());
			}
			if (StringUtils.isNotEmpty(master.getCardPositive())){
				master.setCardPositive(domain + imgUploadLocation+master.getCardPositive());
			}
			if (StringUtils.isNotEmpty(master.getCardNegative())){
				master.setCardNegative(domain + imgUploadLocation+master.getCardNegative());
			}
			if (StringUtils.isNotEmpty(master.getHeadPic())){
				master.setHeadPic(domain + imgUploadLocation+master.getHeadPic());
			}
			JSONObject jobj = JSON.parseObject(master.getSkillType());
			if (jobj.containsKey("1")&&jobj.keySet().size()>1){
				master.setServiceType("2");
			}else if (jobj.containsKey("1")&&jobj.keySet().size()==1){
				master.setServiceType("1");
			}else{
				master.setServiceType("3");
			}
			List<AgentServ> dicts = agentServService.findAgetnServByAgentId(master.getAgentId());
			List<Dict> skillList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(dicts)){
				dicts.forEach(item->{
					Dict dict = new Dict();
					dict.setId(item.getId());
					dict.setCode(item.getServiceClass());
					dict.setValue(item.getServiceCode());
					dict.setName(item.getServiceName());
					if (StringUtils.isNotEmpty(jobj.getString(item.getServiceClass()))){
						dict.setLevel(1);//1选中
					}else{
						dict.setLevel(0);
					}
					skillList.add(dict);
				});
			}
			BeanUtils.copyProperties(master,ch);
			ch.setServiceTypeList(skillList);
		}
		map.put("master", ch);
		return PAGE_FILE_NAME+"detail";
	}

	@RequestMapping(value = {"/data/{id}"})
	public String data(@RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
					   @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize,
					   @PathVariable long id, OrderReq order, ModelMap model) {
		UserMaster master = masterServices.getById(id);
		order.setMasterId(master.getUserId());
		PageInfo<Order> pageInfo = orderService.findAll(pageNum, pageSize, order);
		// pageInfo.list order
		model.put("pageInfo", pageInfo);
		model.put("orderSearch", order);
		model.put("id",id);
		return PAGE_FILE_NAME+"data";
	}



	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult delete(@PathVariable String id, ModelMap map) {
		try {
			UserMaster master = masterServices.getById(id);
			if (masterServices.removeById(id)){
				//更改用户认证状态isMaster
				if (master!=null){
					User user = userService.getById(master.getUserId());
					if (user !=null){
						//被驳回状态
						user.setIsMaster(3);
						if (userService.updateById(user)){
							return JsonResult.success();
						}
					}
				}
			}
		} catch (Exception e) {
			return JsonResult.failure(e.getMessage());
		}
		return JsonResult.success();
	}
}
